package com.cqs.leetcode.ds.union.find;

import com.google.common.base.Stopwatch;
import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class UnionFindClient {

    private static int n;

    public static void main(String[] args) throws IOException {
        String name = "tinyUF.txt";
        name = "mediumUF.txt";
        name = "largeUF.txt";
        File file = new File("/home/li/Documents/algs4-data/" + name);
        List<String> list = Files.readLines(file, Charset.defaultCharset());
        n = Integer.parseInt(list.remove(0));
        union(list, QuickUnion.class);
        union(list, WeightQuickUnion.class);
        union(list, QuickFind.class);

    }


    private static void union(List<String> list, Class<? extends IUnionFind> cls) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        IUnionFind uf = create(cls);
        for (String s1 : list) {
            String[] edge = s1.split(" ");
//            System.out.println("Handling " + s1);
            int start = Integer.valueOf(edge[0]);
            int end = Integer.valueOf(edge[1]);
            uf.union(start, end);
        }
        stopwatch.stop();
        System.out.println(uf.count());
        System.out.println(cls.getSimpleName() + " 运行时间： " + stopwatch.elapsed(TimeUnit.MILLISECONDS) / 1000.0 + "秒");
    }

    private static IUnionFind create(Class<? extends IUnionFind> cls) {
        try {
            Constructor<? extends IUnionFind> constructor = cls.getDeclaredConstructor(int.class);
            return constructor.newInstance(n);
        } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

}
